package com.jiangnan.ui.activity

import android.os.Bundle
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.ViewModelProvider
import com.jiangnan.R
import com.jiangnan.databinding.ActivityOverduePayBinding
import com.jiangnan.util.SharedPrefUtil
import com.jiangnan.util.ToastUtil
import com.jiangnan.util.showConfirmationDialog
import com.jiangnan.util.showQrPaymentDialog
import com.jiangnan.viewmodel.OverduePayViewModel
import java.math.BigDecimal

class OverduePayActivity : BaseActivity() {
    private lateinit var binding: ActivityOverduePayBinding
    private lateinit var vm: OverduePayViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityOverduePayBinding.inflate(layoutInflater)
        setContentView(binding.root)

        vm = ViewModelProvider(this)[OverduePayViewModel::class.java]
        val userId = SharedPrefUtil.getLoginInfo(this)!!.id.toLong()
        if (userId < 0) finish()

        // 观察
        vm.balance.observe(this) { bal ->
            // optionally show balance
        }
        vm.overdue.observe(this) { od ->
            binding.tvOverdue.text = "当前逾期：${"%.2f".format(od)}"
        }
        vm.error.observe(this) { msg ->
            ToastUtil.showShort(this, "当前的余额不足，请先充值")
        }
        vm.toastMessage.observe(this) { msg ->
            ToastUtil.showShort(this, msg)
        }

        // 加载初始
        vm.loadUserInfo(userId)

        // 点击一键缴清
        binding.btnPayOverdue.setOnClickListener {
            val od = vm.overdue.value ?: BigDecimal.ZERO
            if (od <= BigDecimal.ZERO) {
                Toast.makeText(this, "当前无逾期欠款", Toast.LENGTH_SHORT).show()
                return@setOnClickListener
            }

            showConfirmationDialog(
                context = this,
                title = "确认付款",
                message = "本次将支付 ¥${"%.2f".format(od)}，并从账户余额扣除，是否继续？",
                positiveText = "支付",
                negativeText = "取消",
                onConfirm = {
                    vm.payOverdue(userId, od)
                }
            )

        }
    }
}